package other;

import java.util.HashMap;

class LRUCache {
    // 成员
    private static class DLinkedNode {
        int key;
        int value;
        DLinkedNode pre;
        DLinkedNode next;

        DLinkedNode() {
        }

        DLinkedNode(int k, int v) {
            key = k;
            value = v;
        }
    }

    HashMap<Integer, DLinkedNode> cache = new HashMap<>();
    int size;
    int capacity;
    DLinkedNode head, tail;

    public LRUCache(int capacity) {
        this.size = 0;
        this.capacity = capacity;
        head = new DLinkedNode();
        tail = new DLinkedNode();
        head.next = tail;
        tail.pre = head;
    }

    public int get(int key) {
        // 获取元素 key
        DLinkedNode node = cache.get(key);
        if (node == null) {
            return -1;
        }
        moveToHead(node);
        return node.value;
    }

    public void put(int key, int value) {
        DLinkedNode node = cache.get(key);
        if (node == null) {
            node = new DLinkedNode(key, value);
            addToHead(node);
            cache.put(key, node);
            size++;
            if (size > capacity) {
                DLinkedNode last = removeLast();
                cache.remove(last.key);
            }
        } else {
            node.value = value;
            moveToHead(node);
        }
    }

    private DLinkedNode removeLast() {
        DLinkedNode node = tail.pre;
        remove(node);
        return node;
    }

    private void moveToHead(DLinkedNode node) {
        // 先删除 node
        // 再添加 node
        remove(node);
        addToHead(node);
    }

    private void remove(DLinkedNode node) {
        node.pre.next = node.next;
        node.next.pre = node.pre;
    }

    private void addToHead(DLinkedNode node) {
        node.next = head.next;
        head.next.pre = node;
        head.next = node;
        node.pre = head;
    }

}

/**
 * Your LRUCache object will be instantiated and called as such:
 * LRUCache obj = new LRUCache(capacity);
 * int param_1 = obj.get(key);
 * obj.put(key,value);
 */

